package com.kotodama.infrastructure.config;

import com.kotodama.infrastructure.tenant.context.TenantContext;
import com.mongodb.client.MongoClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

/**
 * MongoDB配置类
 * 配置多租户感知的MongoDB操作
 */
@Configuration
public class MongoConfig {

    private final MongoClient mongoClient;
    private final String databaseName;

    public MongoConfig(MongoClient mongoClient) {
        this.mongoClient = mongoClient;
        this.databaseName = "kotodama"; // 默认数据库名
    }

    /**
     * 配置MongoDB转换器
     * 
     * @return MappingMongoConverter实例
     */
    @Bean
    public MappingMongoConverter mappingMongoConverter() {
        MappingMongoConverter converter = new MappingMongoConverter(
                new SimpleMongoClientDatabaseFactory(mongoClient, databaseName),
                new MongoMappingContext());

        // 移除_class字段
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));
        converter.setCustomConversions(new MongoCustomConversions(java.util.Collections.emptyList()));
        converter.afterPropertiesSet();

        return converter;
    }

    /**
     * 配置租户感知的MongoTemplate
     * 
     * @return MongoTemplate实例
     */
    @Bean
    public MongoTemplate mongoTemplate() {
        return new MongoTemplate(
                new SimpleMongoClientDatabaseFactory(mongoClient, databaseName),
                mappingMongoConverter());
    }
}
